package basic

import (
	"encoding/json"
	"fmt"
	"net"
	"strings"
	"testgin0012/chat/common"
	process2 "testgin0012/chat/server/process"
)

type ServerClient struct {
	Conn *net.Conn
	User *common.User
}
type Server struct {
	Address      string
	Network      string
	RedisManager *common.RedisMgr
	Clients      map[int]*ServerClient
	Conns        map[int]*net.Conn
}

var (
	MyServer *Server
)

func NewServer(network string, address string) *Server {
	MyServer = &Server{
		Address:      address,
		Network:      network,
		RedisManager: common.IntRedisPool(),
		Clients:      make(map[int]*ServerClient, 10),
		Conns:        make(map[int]*net.Conn, 10),
	}
	return MyServer
}

func (server *Server) Start() {
	listen, err := net.Listen(server.Network, server.Address)
	if err != nil {
		fmt.Printf("net.Listen err=%v\n", err)
		return
	}
	fmt.Printf("服务器:[%v] 已开启监听\n", server.Address)
	index := 0
	for {
		conn, err := listen.Accept()
		if err != nil {
			fmt.Printf("listen.Accept err=%v\n", err)
			return
		}
		server.Conns[index] = &conn
		fmt.Printf("客户端:[%v] 已连接\n", conn.RemoteAddr().String())
		common.NewConnManager(conn).ResponseString("欢迎加入快乐星球", common.TypeResponseString)
		go server.handleRequest2Response(index)
		index++
	}
}

func (server *Server) handleRequest2Response(index int) {
	conn := *server.Conns[index]
	clientName := conn.RemoteAddr().String()
	defer conn.Close()
	for {
		buffer := make([]byte, 1024)
		i, err3 := conn.Read(buffer)
		if err3 != nil {
			for i, c := range server.Clients {
				if c.Conn == &conn {
					delete(server.Clients, i)
				}
			}
			delete(server.Conns, index)
			fmt.Printf("客户端:[%v] 已退出\n", clientName)
			return
		}
		fmt.Printf("收到客户端的数据为:%v\n", string(buffer[:i]))
		request := common.Request{}
		err := json.Unmarshal(buffer[:i], &request)
		if err != nil {
			fmt.Printf("Message外层json.Unmarshal解码失败, err=%v\n", err)
			return
		}
		connManager := common.NewConnManager(conn)
		userProcess := process2.NewUserProcess()

		buffer, _ = json.Marshal(server)
		fmt.Printf("\n\n服务端现在配置:%v\n\n", string(buffer))

		switch request.Type {
		case common.TypeRequestTest:
			subMessage := &common.RequestTest{}
			err = json.Unmarshal([]byte(request.Data), subMessage)
			if err != nil {
				data := fmt.Sprintf("Message内层json.Unmarshal解码失败, err=%v\n", err)
				connManager.ResponseString(data, common.TypeResponseString)
				continue
			}
			responseSubMessage := &common.ResponseSayOneStart{
				Content: subMessage.Content,
			}
			common.NewConnManager(*server.Clients[11].Conn).ResponseStruct(responseSubMessage, common.TypeResponseTest)
		case common.TypeRequestSayOneStart:
			subMessage := &common.RequestSayOneStart{}
			err = json.Unmarshal([]byte(request.Data), subMessage)
			if err != nil {
				data := fmt.Sprintf("Message内层json.Unmarshal解码失败, err=%v\n", err)
				connManager.ResponseString(data, common.TypeResponseString)
				continue
			}
			responseSubMessage := &common.ResponseSayOneStart{
				FromUser: server.Clients[subMessage.FromUserId].User,
				Content:  strings.Trim(subMessage.Content, "\n\r "),
			}
			common.NewConnManager(*server.Clients[subMessage.ToUserId].Conn).ResponseStruct(responseSubMessage, common.TypeResponseSayOneStart)
		case common.TypeRequestSayOne:
			subMessage := &common.RequestSayOne{}
			err = json.Unmarshal([]byte(request.Data), subMessage)
			if err != nil {
				data := fmt.Sprintf("Message内层json.Unmarshal解码失败, err=%v\n", err)
				connManager.ResponseString(data, common.TypeResponseString)
				continue
			}
			SheUser, ok := server.Clients[subMessage.SheUserId]
			if !ok {
				connManager.ResponseString("用户未登录或者没注册", common.TypeResponseString)
				continue
			}
			responseSubMessage := &common.ResponseSayOne{
				FromUser: server.Clients[subMessage.UserId].User,
				ToUser:   SheUser.User,
			}
			for _, UserId := range []int{SheUser.User.UserId, subMessage.UserId} {
				common.NewConnManager(*server.Clients[UserId].Conn).ResponseStruct(responseSubMessage, common.TypeResponseSayOne)
			}
		case common.TypeRequestSayAll:
			subMessage := &common.RequestSayAll{}
			err = json.Unmarshal([]byte(request.Data), subMessage)
			if err != nil {
				data := fmt.Sprintf("Message内层json.Unmarshal解码失败, err=%v\n", err)
				connManager.ResponseString(data, common.TypeResponseString)
				continue
			}
			otherSubmessage := &common.ResponseSayAll{
				UserId:   subMessage.UserId,
				NickName: server.Clients[subMessage.UserId].User.NickName,
				Content:  subMessage.Content,
			}
			for _, client := range server.Clients {
				if client.User.UserId == subMessage.UserId {
					continue
				}
				common.NewConnManager(*client.Conn).ResponseStruct(otherSubmessage, common.TypeResponseSayAll)
			}
		case common.TypeRequestUserList:
			userList := make(map[int]*common.User)
			for index, client := range server.Clients {
				userList[index] = client.User
			}
			subMessage := common.ResponseUserList{
				UserList: userList,
			}
			connManager.ResponseStruct(subMessage, common.TypeResponseUserList)
		case common.TypeRequestRegister:
			msg, err := userProcess.Register(conn, request)
			if err != nil {
				connManager.ResponseString(err.Error(), common.TypeResponseString)
				continue
			}
			connManager.ResponseString(msg, common.TypeResponseString)
		case common.TypeRequestLogin:
			user, err := userProcess.Login(conn, request)
			if err != nil {
				connManager.ResponseString(err.Error(), common.TypeResponseString)
				continue
			}
			subMessage := common.ResponseLogin{
				UserId:   user.UserId,
				NickName: user.NickName,
			}
			connManager.ResponseStruct(subMessage, common.TypeResponseLogin)
			client := &ServerClient{
				Conn: &conn,
				User: user,
			}
			server.Clients[user.UserId] = client
		}
	}
}
